<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Exceptions\ApiException;
use App\Model\Club\RequestList;
use App\Model\Club\Room;
use App\Model\Club\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ClubLogic extends Logic
{

    public function createLogic($name, $uid)
    {
        $this->checkRequestRec($uid);
        $this->checkClubName($name);
        $this->checkHasCreateClub($uid);
        $this->checkHasJoinClub($uid);
        DB::beginTransaction();
        try {
            DB::table('t_club_member_info')->insert([
                'uid' => $uid,
                'clubid' => DB::table('t_club_info')->insertGetId(['uid' => $uid, 'name' => $name])
            ]);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ApiException('创建俱乐部失败', 4);
        }
    }


    public function joinInLogic($club_id, $uid, $desc)
    {
        $this->checkRequestRec($uid);
        $this->checkHasJoinClub($uid);
        $this->checkRequestStatus($club_id, $uid);
        DB::table('t_club_request_rec')->insert([
            'uid' => $uid,
            'clubid' => $club_id,
            'desc' => $desc,
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }


    public function tableLogic($uid)
    {
        return Table::query()->whereIn('id', function ($query) use ($uid) {
            $query->from('t_club_member_info')->where('uid', $uid)->select(['clubid']);
        })->get();
    }


    public function memberLogic($club_id,$uid)
    {
        $list = DB::table('t_player_info')->whereIn('id', function ($query) use ($club_id) {
            $query->from('t_club_member_info')->where('clubid', $club_id)->select(['uid']);
        })->get(['id', 'nick_name', 'avater_url']);
        if ($list->isEmpty()) {
            return [];
        }
        $last_time = Redis::hGet('CLUB_MEMBER_UPDATE_TIME',$club_id);
        $update_time = DB::table('t_club_member_info')
            ->where('clubid', $club_id)
            ->where('uid','<>',$uid)
            ->orderBy('update_time', 'desc')
            ->value('update_time');
        $is_change = 0;
        if ($update_time > $last_time) {
            $is_change = 1;
            Redis::hSet('CLUB_MEMBER_UPDATE_TIME',$club_id,$update_time);
        }
        return [
            'list' => $list,
            'is_change' => $is_change
        ];
    }


    public function requestListLogic($club_id)
    {
        $list = RequestList::where('clubid', $club_id)->where('status', 0)->get();
        if ($list->isEmpty()) {
            return [];
        }
        $last_time = Redis::hGet('CLUB_REQUEST_UPDATE_TIME',$club_id);
        $create_time = DB::table('t_club_request_rec')->where('clubid', $club_id)
            ->where('status', 0)
            ->orderBy('create_time', 'desc')
            ->value('create_time');
        $is_change = 0;
        if ($create_time > $last_time) {
            $is_change = 1;
            Redis::hSet('CLUB_REQUEST_UPDATE_TIME',$club_id,$create_time);
        }
        return [
            'list' => $list,
            'is_change' => $is_change
        ];
    }


    public function handleRequestLogic($uid, $club_id, $status)
    {
        DB::beginTransaction();
        try {
            if (DB::table('t_club_request_rec')
                ->where('uid', $uid)
                ->where('status', 0)
                ->where('clubid', $club_id)
                ->update(['status' => $status])) {
                DB::table('t_club_member_info')->insert(['uid' => $uid, 'clubid' => $club_id]);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ApiException('handle failure', 7);
        }
    }


    public function exitClubLogic($uid, $user_id, $club_id)
    {
        if (!empty($user_id)) {
            $this->deleteClubMemberLogic($uid, $user_id, $club_id);
            $uid = $user_id;
        } else {
            if (DB::table('t_club_info')->where('id', $club_id)->where('uid', $uid)->value('id')) {
                throw new ApiException('不能退出自己的俱乐部,只能解散自己的俱乐部', 6);
            }
        }
        if (!DB::table('t_club_member_info')
            ->where('uid', $uid)
            ->where('clubid', $club_id)
            ->delete()
        ) {
            throw new ApiException('从俱乐部中删除成员失败', 6);
        }
        //从加入俱乐部流水表中删除记录
        DB::table('t_club_request_rec')->where('uid', $uid)->where('clubid', $club_id)->where('status', 1)->delete();
    }


    private function deleteClubMemberLogic($uid, $user_id, $club_id)
    {
        if (!DB::table('t_club_info')->where('id', $club_id)->where('uid', $uid)->value('id')) {
            throw new ApiException('你不是俱乐部的创始人,不能删除成员', 6);
        }
        if ($uid == $user_id) {
            throw new ApiException('不能删除自己', 6);
        }
    }


    public function dissolveLogic($uid, $club_id)
    {
        if (!DB::table('t_club_info')->where('id', $club_id)->where('uid', $uid)->value('id')) {
            throw new ApiException('你不是这个俱乐部创始人,不能解散', 6);
        }
        if (DB::table('t_club_member_info')->where('clubid', $club_id)->whereNotIn('uid', [$uid])->count('uid') > 0) {
            throw new ApiException('俱乐部还有成员,不能解散', 6);
        }
        DB::beginTransaction();
        if (!DB::table('t_club_member_info')->where('clubid', $club_id)->delete()
            ||
            !DB::table('t_club_info')->where('id', $club_id)->where('uid', $uid)->delete()
        ) {
            DB::rollBack();
            throw new ApiException('解散俱乐部失败', 6);
        }
        DB::commit();
    }


    public function updateClubNameLogic($club_id, $uid, $name)
    {
        $this->checkClubName($name);
        if (!DB::table('t_club_info')->where('id', $club_id)->where('uid', $uid)->update(['name' => $name])) {
            throw new ApiException('修改俱乐部名称失败', 6);
        }
    }

    public function checkClub($param)
    {
        if (empty($param['club_id']) || !is_numeric($param['club_id'])) {
            throw new ApiException('俱乐部id不能为空');
        }
        $object = DB::table('t_club_info')->where('id', $param['club_id'])->first();
        if (empty($object)) {
            throw new ApiException('您查询的俱乐部不存在');
        }
        $object->avater_url = DB::table('t_player_info')->where('id', $object->uid)->value('avater_url');
        return $object;
    }


    public function roomLogic($id)
    {
        $list = Room::where('clubid', $id)->where('status', '<', 3)->get();
        if ($list->isEmpty()) {
            return [];
        }
        return $list;
    }


    /**
     * 校验所创建的俱乐部名称是否已经存在
     * @param $name
     * @throws ApiException
     */
    private function checkClubName($name)
    {
        if (DB::table('t_club_info')->where('name', $name)->value('id')) {
            throw new ApiException('club name exist', 1);
        }
    }

    /**
     * 校验创建的俱乐部是否已经达到限制的数量
     * @param $uid
     * @throws ApiException
     */
    private function checkHasCreateClub($uid)
    {
        if (DB::table('t_club_member_info')->whereIn('clubid', function ($query) use ($uid) {
                $query->from('t_club_info')->where('uid', $uid)->select(['id']);
            })->count('uid') >= 3
        ) {
            throw new ApiException("个人创建俱乐部已经3个", 3);
        }

    }

    /**
     * 校验当前加入的俱乐部是否达到限制数量
     * @param $uid
     * @throws ApiException
     */
    private function checkHasJoinClub($uid)
    {
        if (DB::table('t_club_member_info')->where('uid', $uid)->count('uid') >= 5) {
            throw new ApiException('个人加入俱乐部已经5个', 2);
        }
    }


    /**
     * 校验请求加入俱乐部的状态
     * @param $club_id
     * @param $uid
     * @throws ApiException
     */
    private function checkRequestStatus($club_id, $uid)
    {
        //查看是否已经申请过加入该俱乐部
        $status = DB::table('t_club_request_rec')
            ->where('clubid', $club_id)
            ->where('uid', $uid)
            ->whereIn('status', [0, 1])
            ->value('status');
        if (!is_null($status)) {
            if (0 === (int)$status) {
                throw new ApiException('已经请求加入该俱乐部,待处理本次请求加入', 6);
            }
            if (1 === (int)$status) {
                throw new ApiException('已经申请通过加入该俱乐部', 6);
            }
        }
        //校验是否已经加入了这个了这个俱乐部
        if (DB::table('t_club_member_info')->where('uid', $uid)->where('clubid', $club_id)->value('uid')) {
            throw new ApiException('已经加入了该俱乐部');
        }
    }


    /**
     * 申请加入俱乐部和创建个人俱乐部时,判断请求表中的待处理数是否达到5次
     * 如果达到5次不能再进行创建和申请加入操作,防止出现个人俱乐部数量超标
     * @param $uid
     * @throws ApiException
     */
    private function checkRequestRec($uid)
    {
        if (DB::table('t_club_request_rec')->where('uid', $uid)->where('status', 0)->count('id') >= 5) {
            throw new ApiException('申请加入俱乐部请求已经达到5次,待处理后再进行申请和创建的操作', 6);
        }
    }


}